<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
    <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<!doctype html>
<html>
<head>
<jsp:include page="/common/commonCss.jsp"/>
<jsp:include page="/common/commonJs.jsp"/>
<script src="${basePath}commonJs/jquery.ztree.all.js"></script>
<title>嘉童游乐中心-新增采购订单清单</title>

	<SCRIPT type="text/javascript">
		 
	 //标记被选中节点
	var selectNode=null;
	var treeNodes=[];
	var setting = {
		data: {
			simpleData: {
				enable: true
			}
		},
		callback:{
			onClick:zTreeonclick
		}
	};
	$(document).ready(function(){
		initParams();
		getTreeData();
		$.fn.zTree.init($("#sptree"), setting, treeNodes);
		setDefaultForTree();
		initpriceSupRrd();
		purOrderPrdDiv('');
		
		
	});
	function zTreeonclick(event, treeId, treeNode) {
		var tId=treeNode.tId;
		if(tId!="sptree_1"){
			$("#sptree_1_a").removeClass("curSelectedNode");
		}
		selectNode = treeNode;// 每次点击赋值 
		$("#resverseType").val(selectNode.resverseType);
		var  fkPrdcateId=treeNode.id;
		$("#fkPrdcateId").val(fkPrdcateId);
		$("#pageNo").val("1");
		initParams();
	};
	 
	//设置ztrre默认选中,以及样式
	function setDefaultForTree(){
		$("#sptree_1_a").addClass("curSelectedNode");
		selectNode=treeNodes[0];
		$("#resverseType").val(selectNode.resverseType);
	}	 
		
	//初始化参数
	function initParams() {
		setRadioVal();
		$("#pageNo").val("1");
		var myform = $("#productInfo");
		var pagebean = new PageBean(myform);
		pagebean.setTableId("showData");
		pagebean.setFootId("foot");
		pagebean.setCallback(showData);
		setPagebeanObj(pagebean); //全局化pageBean对象
		pagebean.doPage();  //执行分页
	}
	/*得到商品分类的数据信息*/
	function   getTreeData(){
				$.ajax({
						url:"${basePath}scmInvocing/productInfo/findCategoryList.shtml",
						dataType:"json",
						type:"post",
	      	 			async:false,
	      	 			success:function(result){
	      	 				var node;
	      	 				$(result).each(function(id,item){
	      	 					if(id==0){
		      	 					node={id:item.pkPrdcateId,pId:item.fkParPrdcateId,name:item.cateName,open:true,reserveFlag:item.reserveFlag,resverseType:item.resverseType};
	      	 					}else{
		      	 					node={id:item.pkPrdcateId,pId:item.fkParPrdcateId,name:item.cateName,reserveFlag:item.reserveFlag,resverseType:item.resverseType};
	      	 					}
	      	 					treeNodes.push(node);
	      	 				});
	      	 			}
					
				});
	}
	//展示数据
	function showData(result){
		var id='selectAll';
		$(result).each(function(index,item){
			var html="<tr>";
			var purOrderId =item.purOrderId;
			var ischecked="";
			if(purOrderId !="" && purOrderId !=null){
				ischecked="checked";
			}
			 html+="<td><input type='checkbox' value="+item.pkPrdId+" "+ischecked+" name='codebox' class='idFlag' onclick='SelectBoxOne(this)'></td>";
			 html+="<td>"+(index+1)+"</td>";
			 html+="<td class='lv'><a href='#' onclick='findProductById(this);' pkPrdId="+item.pkPrdId+"  resverseType="+item.resverseType+">"+item.pkPrdId+"</a></td>";
			 html+="<td>"+item.prdName+"</td>";
			 html+="<td>"+item.cateName+"</td>";
			 if(item.prdSpec==""||item.prdSpec==null){
				 html+="<td>无</td>";
			 }else{
				 html+="<td>"+item.prdSpec+"</td>";
			 }
			 if(item.unitName==""||item.unitName==null){
				 html+="<td>无</td>";
				 
			 }else{
				 html+="<td>"+item.unitName+"</td>";
			 }
			 if(item.comments==null||item.comments==""){
				 html+="<td>无</td>";
			 }else{
			 	html+="<td>"+item.comments+"</td>";
			 }
			 if(item.prdStatus=='1'){
				 html+="<td>正常</td>";			 
			 }else if(item.prdStatus=='2'){
				 html+="<td>停用</td>";
			 }else{
				 html+="<td>未定价</td>";
			 }
			 html+="</tr>";
			$("#showData").find("tr:eq("+index+")").after(html);
		});
		
		 
	}
	
	//查询商品信息
	function findProductList(){
			initParams();
	}
	//将选中的radio赋值
	function setRadioVal(){
		var selVal=$("#tPrdStatus option:selected").val();
		$("#prdStatus").val(selVal);
	}
	
	//设置全选按钮全选
	function setSelectAll(id,thisobj){
		var idList=[];
		if($(thisobj).attr("checked")=="checked"){
				$("."+id).attr("checked",true);
		}else{
			$("."+id).attr("checked",false);
		}
	}
	
	function SelectBoxOne(o){//单选 选中，或取消 商品树列表 
		var pkPurordId ='${pkPurordId}';
		var supplyIds=$("#selectScmSupid").val();
	 
		var type="add";
	            if (o.type=="checkbox" && o.checked){      
	            }else{
	            	 type="cancel";      
	            }  
	     var url="${basePath }scmInvocing/scmPurOrder/insertPurOrderPrd.shtml?fkPurordId="+pkPurordId+"&fkPrdId="+o.value+"&type="+type+"&scmSupIds="+supplyIds;
			$.ajax({
				   url: url,
				   type: 'get',
				      async:false, 
				   success:function(msg){
						if (msg != "1") {
							 if(msg =="2"){
								 alertWarning("此商品暂时没有 供应商供货。请先添加供应商及供应商协议。");
							 }else{
								 alertWarning("选取商品失败。");
							 }
							 o.checked =false;
						}else{
						}
				   }
			 });
	}
	
	function selectAll(){//全选 选中，或取消 商品树列表 
		var pkPurordId ='${pkPurordId}';
		var type="add";
		var supplyIds=$("#selectScmSupid").value;
             var checklist = new Array();
             $("[name = codebox]:checkbox").each(function () {
            	
                 if ($("#selectAll").is(":checked")) {
                	 $("[name = codebox]:checkbox").attr("checked", true);
                 }else{
                	 type="cancel";   
                	   $(this).attr("checked", !$(this).attr("checked"));
                 }
                 checklist.push($(this).attr("value"));
             });

           //  checklist.join(",") ;
		 
		 if(checklist.length>0){

		    $("#hide_loading").show();
		    var url="${basePath }scmInvocing/scmPurOrder/addPurOrderPrdBatch.shtml";
			$.ajax({
				   url: url,
				   type: 'post',
				   data:"fkPurordId="+pkPurordId+"&fkPrdIds="+checklist+"&type="+type+"&scmSupIds="+supplyIds,
				      async:false, 
				   success:function(msg){
						if (msg != "1") {
							 
						}else{
						}
						$("#hide_loading").hide();
				   }
			 });
			
		 }else{
			 //alertWarning("系统无商品。");
		 }
		}

	 
	function reset(){
		document.getElementById("pkPrdId").value="";
		document.getElementById("prdName").value="";
		initParams();
	}
	
	function purOrderPrdDiv(divType){//采购商品目录 列表
		if(divType!=""){
			 $("#hide_loading").show();
		}
		var supplyIds=$("#selectScmSupid").val();
		var supplyId="";
		if(supplyIds!=""){
			var supplyArray =supplyIds.split("@");
			supplyId =supplyArray[0];
		}
		 var pkPurordId ='${pkPurordId}';
	     var url="${basePath }scmInvocing/scmPurOrder/findPurOrderPrdByOrderId.shtml?fkPurordId="+pkPurordId+"&supplyId="+supplyId;
			$.ajax({
				   url: url,
				   type: 'get',
				      async:false, 
				      success:function(data){
							if (data != null) {
								var jsonarray ;
								 for(var o in data){  
									 if(o=="listScmPurordPrd"){
										 jsonarray=data[o];
										 var html='<table class="table">';
										 html +='<tr><th>序号</th><th>商品编号</th><th>商品名称</th><th>商品分类</th>';
										 html +='<th>规格</th><th>单位</th><th>协议单价(元)</th> <th>采购数量</th> <th>操作</th>'; 
										 html +='</tr>';
										 if(jsonarray!=null && jsonarray.length>0){
										 for (var k = 0; k < jsonarray.length; k++) {
												  var jsonobj = jsonarray[k];
										   if(jsonobj!=null){
											  var unitName =jsonobj["unitName"];
											  if(unitName ==null){
												  unitName="";
											  }
											  var prdSpec =jsonobj["prdSpec"];
											  if(prdSpec ==null){
												  prdSpec="";
											  }
											  var fkPrdId =jsonobj["fkPrdId"];
											  if(fkPrdId ==null){
												  fkPrdId="";
											  }
											    html +="<tr>";
										      var prdName=jsonobj["prdName"];
										      var supplyId =jsonobj["supplyId"];
										      var purcnt =0;
										      var amgPrice="-";
										        purcnt =jsonobj["purCnt"];
										        var purPrice =jsonobj["purPrice"];
										        var agmPrice =jsonobj["agmPrice"];
										        var fkSupagmIds =jsonobj["fkSupagmId"];
										        alert(fkSupagmIds);
												 //===
													  html+='<td>'+(k+1)+'</td>';
													 html+='<td>'+fkPrdId+'</td>';
													 html+='<td>'+jsonobj["prdName"]+'</td>';
													 html+='<td>'+jsonobj["prdCateName"]+'</td>';
													 html+='<td>'+prdSpec+'</td>';
													 html+='<td>'+unitName+'</td> ';
													 html+='<td><div id="priceDiv'+fkPrdId+'">'+agmPrice+'</div></td> ';
													 html+='<td><input type="text" onkeyup="yazhengbigNum(this)" name="purCnt" id="purCnt'+fkPrdId+'" class="iput_t w82" value="'+parseInt(purcnt)+'"/><input type="hidden" name="fksupAgmId" id="fksupAgmId'+fkPrdId+'" value="'+fkSupagmIds+'"/><input type="hidden" name="agmPrice" id="agmPrice'+fkPrdId+'" value="'+agmPrice+'"/><input type="hidden" name="scmSupId" id="scmSupId@'+fkPrdId+'" value="'+supplyId+'"/><input type="hidden" name="fkPrdIds" value="'+fkPrdId+'"/></td><input type="hidden" name="fkPrdName"  id="PrdName'+fkPrdId+'" value="'+prdName+'"/></td> ';
													var delpurPrd ="del_purOrderPrd('"+fkPrdId+"')";
													 html+='<td><input type="button" class="btn_l" onclick="'+delpurPrd+'" value="删除"/></td>  ';
												 //===
												 html+="</tr>";
													//$("#tablesupPrd").find("tr:eq("+k+")").after(html);
										  }
										 }   
										 }
										 html +='</table>';
										 $("#tablesupPrd").html(html);
									 } 
									
									
								 }
								
								 initpriceSupRrd();//初始化 供应商 协议价格，协议id 
								 
							}else{
								 $.messager.alert('提示','添加采购商品失败！','error');
							}
							if(divType!=""){
							 $("#hide_loading").hide();
							 $('#addSelectGoods').window('close');
							}
					   }
			 });
	}
	
	function getSelectIds(prdId){
		 var selectId ="selectSup@"+prdId;
			var obj = document.getElementById(selectId); //定位id
			var index = obj.selectedIndex; // 选中索引
			//var text = obj.options[index].text; // 选中文本
			var value = obj.options[index].value; // 选中值
			return value;
	}
	function selectSupId(oid){// 触发供应商 下拉框 onchange 事件
		 var value =$("#selectScmSupid").val();
		 if(value ==""){
			 alertWarning("请选择供应商。");
		 }else{
			 purOrderPrdDiv('');
			 refreshSelect();
		 }
	}
	
	/**初始化 供应商 协议价格，协议id 
	**/
	function initpriceSupRrd(){//初始化 供应商 协议价格，协议id 
		 if('${oldSuppLyId}' != ''){
			 $("#selectScmSupid").val('${oldSuppLyId}');
				refreshSelect();
		 }
			

		} 
	
	function saveSupRrd(saveType,purStatus){
		var supplyIds=document.getElementById("selectScmSupid").value;
		if(supplyIds==""){
			 alertWarning("请选择供应商！");
			 return;
		} 
		 var pkPurordId ='${pkPurordId}';
		 var url ='${basePath }scmInvocing/scmPurOrder/savePurOrderPrdBatch.shtml?saveType='+saveType+'&fkPurordId='+pkPurordId+'&scmSupIds='+supplyIds+'&purStatus='+purStatus;
		 if(purStatus=='1'){
			$.ajax({
				   url: url,
				   type: 'POST',
				   data:$("#supPrdForm").serialize(),//序列化表单里所有的内容
				      async:false, 
				   success:function(msg){
						if (msg != "1") {
							alertInfo("保存失败！");
						}else{
							alertInfo("保存成功！");
						}
				   }
			});
			
	 }else{
		  $.messager.confirm('提示', '确认要提交吗?', function(r) {
				if(r){
					$.ajax({
						   url: url,
						   type: 'POST',
						   data:$("#supPrdForm").serialize(),//序列化表单里所有的内容
						      async:false, 
						   success:function(msg){
								if (msg != "1") {
									alertInfo("提交失败！");
								}else{
									alertInfo("提交成功！");
								}
						   }
					});
				}
			 });
	 }
	}
	
	function addPurPrd(){
		var supplyIds=document.getElementById("selectScmSupid").value;
		if(supplyIds==""){
			 alertWarning("请选择供应商！");
			 return;
		} else{
			initParams();
			$("#selectAll").attr("checked", false);
			$('#addSelectGoods').window('open');
			
		}
	}
	
	 function del_purOrderPrd(id){
		 var pkPurordId ='${pkPurordId}';
		 $.messager.confirm('提示', '确认要删除吗?', function(r) {
			if(r){
				$.ajax({ 
					url: "${basePath }scmInvocing/scmPurOrder/delPurOrderPrd.shtml",
					data:"fkPrdId="+id+"&fkPurordId="+pkPurordId,
					type:'POST',
					success: function(data){
						purOrderPrdDiv('');
						alertInfo($common_delete_success);
			      	}
				});
			}
		 });
	 }
	
	</SCRIPT>
</head>
<body class="bg">
<div class="content m_auto">
	<div class="content_l mt10">
    	<ul>
        	      <shiro:hasPermission name="scmInvocing/productInfo/forwardToProductInfo.shtml">
    				  <li><a href="${basePath}scmInvocing/productInfo/forwardToProductInfo.shtml"><i class="nav_icon_b"></i><br>商品信息</a></li>
    		</shiro:hasPermission>
    		 <shiro:hasPermission name="scmInvocing/countUnit/forwardToUnitInfo.shtml">
    		 		<li><a href="${basePath}scmInvocing/countUnit/forwardToUnitInfo.shtml"><i class="nav_icon_b"></i><br>单位设置</a></li>
    		 </shiro:hasPermission>
    		 <shiro:hasPermission name="scmInvocing/supplier/forwardToSupply.shtml">
    		 		   <li><a href="${basePath}scmInvocing/supplier/forwardToSupply.shtml"><i class="nav_icon_a"></i><br>供应商信息</a></li>
    		 </shiro:hasPermission>
    		  <shiro:hasPermission name="scmInvocing/priceManager/forwardToList.shtml">
    		 		  <li><a href="${basePath}scmInvocing/priceManager/forwardToList.shtml"><i class="nav_icon_f"></i><br>价格管理</a></li>
    		 </shiro:hasPermission>
    		   <shiro:hasPermission name="scmInvocing/scmPurOrder/findInvoPurOrder.shtml">
            	  <li  class="content_hover"><a href="${basePath}scmInvocing/scmPurOrder/findInvoPurOrder.shtml"><i class="nav_icon_b"></i><br>采购订单</a></li>
    		 </shiro:hasPermission>
    		   <shiro:hasPermission name="scmInvocing/scmPayForm/findInvoOrderPay.shtml">
           		   <li><a href="${basePath}scmInvocing/scmPayForm/findInvoOrderPay.shtml"><i class="nav_icon_b"></i><br>付款申请</a></li>
    		 </shiro:hasPermission></ul>
    </div>
    <div class="content_r mt10">
    	<div class="p20">
            <div class="file_single_dl f14 fixed">
                <h1 class=""><font size="+1">采购订单清单</font></h1>
                <hr>
                <dl class="fixed" style="overflow:hidden"> 
                    
                     <c:choose>
		                  <c:when test="${type=='add'}">
		                      <dd><label>采购订单编号：</label></dd>
		                   </c:when>
		                    <c:otherwise>
		                          <dd><label>采购订单编号：</label>${pkPurordId}</dd>
		                     </c:otherwise>
                      </c:choose>
                </dl>
                <hr>
                <dl class="fixed" style="overflow:hidden">
                    <dd><label>制单人：</label>${userName}</dd>
                    <dd><label>制单单位：</label>${brandName}</dd>
                    <dd>
                    <label>供应商：</label>
                     <div class="uboxstyle"> 
                           <select name="selectScmSupid" id="selectScmSupid" onchange="selectSupId(this)">
                            <option value="">请选择供应商</option>
                            <c:forEach items="${scmSupList}" var="scmSupply" varStatus="status">
			                        <option value="${scmSupply.pkSupId}" >${scmSupply.supName}</option>
                             </c:forEach>
                           </select>
                       </div>
                    </dd>
                </dl>
                <hr>
            </div>
           
            <div class="mt10">
                <h1 class=""><font size="+1">采购商品目录</font></h1>
                <ul class="fixed" id="tab_conbox_a">
                    <li class="p10 h450">
                    <form action="" id="supPrdForm">
                             <div  id="tablesupPrd">
                		</div>
                        </form>
                        <div class="btm_btn m10">
                            <dl>
                            	<dd><input class="btn" type="button" value="新增" onClick="addPurPrd()"></dd>
                            	<dd><input class="btn" type="button" value="保存" onClick="saveSupRrd('save','1')"></dd>
                                <dd><input class="btn" type="button" value="提交" onClick="saveSupRrd('tijiao','2')"></dd>
                                <dd><input class="btn" type="button" value="返回" onClick="javascript:window.location.href='${basePath}scmInvocing/scmPurOrder/findInvoPurOrder.shtml'"></dd>
                               <dd><input class="btn" type="button" value="打印" ></dd>
                                
                            </dl>
                        </div>
                            
                          
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>
<!---弹出层 商品树列表信息编w辑--->
<div id="addSelectGoods" class="easyui-window" title="新增采购商品" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:1200px; height:520px;position:relative;">
    	<div class="file_single_dl f14 fixed p10">
    		<form id="productInfo" action="${basePath}scmInvocing/scmPurOrder/findProductListJoinOrderPrd.shtml">
    		<input type="hidden" name="pageNo" id="pageNo" value="1">
    		<input type="hidden" name="pageSize" value="8">
    		
    			<input type="hidden" name="purOrderId" id="purOrderId" value="${pkPurordId}"/>
    	   	<input type="hidden" name="prdStatus" id="prdStatus" value=""/>
    	   	<input type="hidden" name="fkPrdcateId" id="fkPrdcateId" value=""/>
        	<dl class="fixed fl">
            	<dd><label>商品编号：</label><input type="text" class="iput_t " name="pkPrdId" id="pkPrdId"></dd>
                <dd><label>商品名称：</label><input type="text" class="iput_t " name="prdName" id="prdName"></dd>
            </dl>
            </form>
            <div>
              <input type="button" class="btn fl ml10" value="查询" onclick="findProductList();">
              <!-- <input type="button" class="btn fl ml10" value="重置" onclick="reset();">  -->
            </div>
        </div>
        <div class="tab_normal mt10">
            <ul class=" fixed" id="tab_a"></ul>
            <div class="payment_l tc" style="height:410px !important">
              <div class="ztree m10" id="sptree" style="overflow-y: auto;overflow-x: auto;width: 270px; height: 412px;">
                 </div>
            </div>
            <div style=" width:850px;" class="m10 fl">
                <table class="table mt10" id="showData">
                    	<tr>
                       		 <th><input type="checkbox" id="selectAll"    onclick="selectAll()"/></th>
                        	<th>序号</th>
                            <th>商品编号</th>
                            <th>商品名称</th>
                            <th>商品分类</th>
                            <th>规格</th>
                            <th>计量单位</th>
                            <th>备注</th>
                            <th>状态</th> 
                        </tr>
                    </table>
                    <!-- 翻页 -->
               	 <div class="page fr m10" id="foot">
                        
                  </div>
                  <br/>
                   <input class="btn mt10" type="button" value="确定" onclick="purOrderPrdDiv('divClose')">
			</div>
		</div>
		  
</div>

    
</div>
<div id="hide_loading">
	<div class="loading"></div>    
    <div class="loading_bg"></div>	
</div>
</body>
</html>